import socket
import re
import time

def service_client(client_socket,recv_data):
    
    #recv/send接受发送数据额
    recv_list =recv_data.splitlines()
    req = re.search(r"/[^ ]*",recv_list[0]).group()
    if req:
        if req == '/':
            req = '/index.html'
    print(req)
    try:
        with open('D:\python\jichuu\Web服务器\moban897'+req,'rb') as f:
            response_body = f.read()
    except :
        response_header ="HTTP/1.1 404 NOT FOUND\n\r\n"
        response_body = '<h1>nonono</h1>'
        response_body = response_body.encode('utf-8')
        
    else:
        response_header ="HTTP/1.1 200 OK\n"
        response_header += "Content-Length:%d\n\r\n" %(len(response_body))

    response_header = response_header.encode('utf-8')
    response = response_header + response_body
    client_socket.send(response)
    client_socket.close()
    
def main():
    #  socket创建一个套接字
    tcp_server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    tcp_server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)  
    #一定要绑定IP和端口，就跟110一样，是固定的让人随时能知道
    tcp_server.bind(('192.168.124.32',7890))
    #listen使套接字变成可以被动链接
    tcp_server.listen(128)
    tcp_server.setblocking(False)
    client_list = list()
    #  循环为多个客户端服务
    while True:
        try:
            print('等人')
            #accept等待客户端的链接
            new_socket,client_add = tcp_server.accept()
        except Exception as ret:
            pass
        else:
            print('人来了')
            new_socket.setblocking(False)
            client_list.append(new_socket)
            
        for client_socket in client_list:
            try:
                recv_data = client_socket.recv(1024).decode("utf-8")
            except Exception as ret:
                pass
            else:
                print('来数据了')
                if recv_data:
                    service_client(client_socket,recv_data)
                else:
                    client_socket.close()
                    client_list.remove(client_socket)
                
    tcp_server.close()
    
if __name__ == '__main__':
    main()
